package org.offerproject.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.offerproject.shortlink.admin.common.convention.exception.ClientException;
import org.offerproject.shortlink.admin.dao.eneity.UserDO;
import org.offerproject.shortlink.admin.dao.mapper.UserMapper;
import org.offerproject.shortlink.admin.dto.req.UserLoginReqDTO;
import org.offerproject.shortlink.admin.dto.req.UserRegisterReqDTO;
import org.offerproject.shortlink.admin.dto.req.UserUpdateReqDTO;
import org.offerproject.shortlink.admin.dto.resp.UserLoginRespDto;
import org.offerproject.shortlink.admin.dto.resp.UserRespDto;
import org.offerproject.shortlink.admin.service.UserService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static org.offerproject.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static org.offerproject.shortlink.admin.common.enums.UserErrorCodeEnum.*;

/**
 * Classname: UserServiceImpl
 * Package: org.offerproject.shortlink.admin.service.impl
 * Description:
 *
 * @author: 杨晨辉
 * @CreateTime: 2024/9/5 16:13
 * @version: 1.0
 */

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public UserRespDto getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null){
            throw new ClientException(USER_NOT_EXIST);
        }
        UserRespDto result = new UserRespDto();
        BeanUtils.copyProperties(userDO,result);
        return result;
    }

    @Override
    public Boolean hashUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if(hashUsername(requestParam.getUsername())){
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());

        try {
            if(lock.tryLock()){
                int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                if(insert < 1){
                    throw new ClientException(USER_SAVE_ERROR);
                }
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {

        // 验证当前登录用户是否与修改用户一致
        if(!hashUsername(requestParam.getUsername())){
            throw new ClientException(USER_NOT_EXIST);
        }

        LambdaQueryWrapper<UserDO> updateWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        int update = baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class),updateWrapper);

    }

    @Override
    public UserLoginRespDto login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> loginWrapper = Wrappers.lambdaQuery(UserDO.class)
                        .eq(UserDO::getUsername,requestParam.getUsername())
                        .eq(UserDO::getPassword,requestParam.getPassword())
                        .eq(UserDO::getDelFlag,0);
        UserDO userDO = baseMapper.selectOne(loginWrapper);

        if(userDO == null){
            throw new ClientException(USER_NOT_EXIST);
        }
        Boolean hasKey = stringRedisTemplate.hasKey("login_" + requestParam.getUsername());
        if(hasKey){
            throw new ClientException("用户已登录");
        }
        /**
         * Hash
         * Key: login_用户名
         * value:
         * key:token
         * val:Json 字符串 (用户信息)
         */
        String md5 = MD5.create().toString();
        stringRedisTemplate.opsForHash().put("login_" + requestParam.getUsername(),md5,JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_" + requestParam.getUsername(),30L, TimeUnit.MINUTES);
        return new UserLoginRespDto(md5);
    }

    @Override
    public Boolean checkLogin(String username,String token) {
        return stringRedisTemplate.opsForHash().get("login_"+username,token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if(checkLogin(username,token)){
            stringRedisTemplate.opsForHash().delete("login_"+username,token);
            return;
        }
        throw new ClientException("用户未登录");
    }


}
